package gdut.jmxywz.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import gdut.jmxywz.been.ClassDown;
import gdut.jmxywz.been.TableFiles;
import gdut.jmxywz.been.Teacher;
import gdut.jmxywz.been.TeachingFiles;
import gdut.jmxywz.util.PageModel;

public class TableFilesAction extends BaseAction {

	public static final String TEACHER_SESSION_KEY = "teacherSessionKey";
	
	private TableFiles tableFiles;
	
	private Teacher teacher;
	
	private String tablefileName;
	
	private String tableFileContext;
	
	private int tableId;
	
	private int auditType;
	
	private int auditState=5;
	
	private int personalType=0;
	
	private int teacherId;
	
	/*----------------分页----------------------*/
	private PageModel pageModel;
	
	private int currentPage=1;
	
	private int pageSize=5;

/*----------------检索----------------------*/
	private String searchSelect="";
	
	private String like="like";
	
	private String searchValue="";
	
/*-----------------上传---------------------*/	
	private File uploadFile;
	
	private String uploadFileFileName;
	
	private String uploadFileContentType;

/*----------------下载----------------------*/
	private String fileDownSaveName;
	
	private String fileUrl;
	
	private InputStream inputStream;
	
	private String contentType;

/*======================setter和getter方法==========================*/
	public TableFiles getTableFiles() {
		return tableFiles;
	}

	public void setTableFiles(TableFiles tableFiles) {
		this.tableFiles = tableFiles;
	}

	public Teacher getTeacher() {
		return teacher;
	}

	public void setTeacher(Teacher teacher) {
		this.teacher = teacher;
	}

	public PageModel getPageModel() {
		return pageModel;
	}

	public void setPageModel(PageModel pageModel) {
		this.pageModel = pageModel;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getSearchSelect() {
		return searchSelect;
	}

	public void setSearchSelect(String searchSelect) {
		this.searchSelect = searchSelect;
	}

	public String getLike() {
		return like;
	}

	public void setLike(String like) {
		this.like = like;
	}

	public String getSearchValue() {
		return searchValue;
	}

	public void setSearchValue(String searchValue)throws UnsupportedEncodingException {
		this.searchValue = new String(searchValue.getBytes("ISO-8859-1"),"utf-8");
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public String getUploadFileContentType() {
		return uploadFileContentType;
	}

	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}

	public String getFileDownSaveName() {
		return fileDownSaveName;
	}

	public void setFileDownSaveName(String fileDownSaveName) {
		this.fileDownSaveName = fileDownSaveName;
	}

	public String getFileUrl() {
		return fileUrl;
	}

	public void setFileUrl(String fileUrl) {
		this.fileUrl = fileUrl;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	
	public String getTablefileName() {
		return tablefileName;
	}

	public void setTablefileName(String tablefileName) {
		this.tablefileName = tablefileName;
	}

	public String getTableFileContext() {
		return tableFileContext;
	}

	public void setTableFileContext(String tableFileContext) {
		this.tableFileContext = tableFileContext;
	}
	
	public int getTableId() {
		return tableId;
	}

	public void setTableId(int tableId) {
		this.tableId = tableId;
	}

/*匹配文件类型*/
	public String getContentType(String contentType) {
		for( String ext : contentTypes.keySet() ) {
			if( fileUrl.toLowerCase().endsWith( ext ) ) {
				return contentTypes.get( ext );
			}
		}
		return "application/octet-stream";
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

/*列出可能用到的文件格式匹配类型，用于getContentType(String contentType)中匹配*/

	static Map<String, String> contentTypes = new HashMap<String, String>();
	static {
		
		contentTypes.put("docx", "application/msword");
		contentTypes.put("xlsx", "application/vnd.ms-excel");
		contentTypes.put("pptx", "application/vnd.ms-powerpoint");
		contentTypes.put("doc", "application/msword");
		contentTypes.put("xls", "application/vnd.ms-excel");
		contentTypes.put("ppt", "application/vnd.ms-powerpoint");
		contentTypes.put("pdf", "application/pdf");
		contentTypes.put("exe", "application/octet-stream");
		contentTypes.put("bin", "application/octet-stream");
		contentTypes.put("zip", "application/zip");
		contentTypes.put("htm", "text/html");
		contentTypes.put("html", "text/html");
		contentTypes.put("gif", "image/gif");
		contentTypes.put("bmp", "image/bmp");
		contentTypes.put("jpg", "image/jpeg");
		contentTypes.put("jpeg", "image/jpeg");
		contentTypes.put("mpeg", "video/mpeg");
	}
	
	public int getAuditType() {
		return auditType;
	}

	public void setAuditType(int auditType) {
		this.auditType = auditType;
	}

	public int getAuditState() {
		return auditState;
	}

	public void setAuditState(int auditState) {
		this.auditState = auditState;
	}
	
	public int getTeacherId() {
		return teacherId;
	}

	public void setTeacherId(int teacherId) {
		this.teacherId = teacherId;
	}
	
	public int getPersonalType() {
		return personalType;
	}

	public void setPersonalType(int personalType) {
		this.personalType = personalType;
	}

	/*##################################################################################*/
	public String Add() throws Exception {
		// TODO Auto-generated method stub
		teacher=(Teacher)ActionContext.getContext().getSession().get(TEACHER_SESSION_KEY);
		if(teacher==null)return "input";
		if(uploadFile==null)return "returnAdd";
		
		/*
		 * 重命名文件
		 */
		String extendName=uploadFileFileName;
		/*截取扩展名*/
		if(extendName.lastIndexOf(".")==-1){
			extendName="";
		}else{
			extendName=extendName.substring(extendName.lastIndexOf("."));
		}
		/*用时间生成字符串*/
		java.text.DateFormat df=new java.text.SimpleDateFormat("yyMMddHHmmss");
		String dateString=df.format(new Date());
		/*用随机数和TeacherId生成字符串*/
		Random random=new Random();
		int randomNum = random.nextInt(911)*teacher.getTeacherId()%99+1;
		String randomString = String.valueOf(randomNum);
		if(randomString.length()==1){
			randomString="0"+randomString;
		}
		/*文件存储路径*/
		String newFileUrl="\\tableFiles\\"+dateString+randomString+extendName;
		System.out.println("-------------------------------------"+newFileUrl+ServletActionContext.getServletContext().getRealPath("/"));
		/*将读入的文件写到指定路径中*/
		FileOutputStream fos=new FileOutputStream(ServletActionContext.getServletContext().getRealPath("/")+newFileUrl);
		FileInputStream fis=new FileInputStream(uploadFile);
		byte[] buffer=new byte[1024];
		int len=0;
		while((len=fis.read(buffer))>0){
		fos.write(buffer,0,len);
		}
		/*存文件*/
		if(tablefileName.length()==0)tablefileName=this.getUploadFileFileName();
		if(tableFileContext.length()==0)tableFileContext=this.getUploadFileFileName();
		tableFiles=new TableFiles();
		tableFiles.setTableFileUrl(newFileUrl);
		tableFiles.setTablefileName(tablefileName);
		tableFiles.setTableFileContext(tableFileContext);
		tableFiles.setTeacher(teacher);
		tableFiles.setDownloadTime(0);
		tableFiles.setUploadTime(new Date());
		tableFiles.setAuditing(0);
		
		boolean bl=this.getCommonService().saveObject(tableFiles);
		if(!bl){
			return "error";
		}
		
		if(personalType==1){
			return "personalAdd";
		}
		
		return "add";
	}
	
	public String Show() throws Exception {
		// TODO Auto-generated method stub
		String hql="from TableFiles tf order by tf.uploadTime desc";
		pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize, "tableFilesShow.action", "");
		if(pageModel.getList()!=null){
			for(int i=0;i<pageModel.getList().size();i++){
				tableFiles=(TableFiles)pageModel.getList().get(i);
				/*设置日期格式*/
				java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd");
				tableFiles.setUploadTime(df.parse(df.format(tableFiles.getUploadTime())));
			}
		}
		personalType=0;
		return "show";
	}
	
	public String Search() throws Exception {
		// TODO Auto-generated method stub
		String hql="from TableFiles";
		String searchParameter="";
		String searchValue1=searchValue;
		if (like.equals("like")) {
			hql = hql + " as bf  where bf." + searchSelect + " like '%"+ searchValue1 + "%'";
		} else {
			hql = hql + " as bf  where bf." + searchSelect + " ='"+ searchValue1 + "'";
		}
		
		if(personalType==1){
			hql=hql+" and bf.teacher.teacherId="+teacherId;
		}
		
		if(personalType==2){
			hql=hql+" and bf.auditing in (1,2)";
		}
		
		String enSearchValue=java.net.URLEncoder.encode(searchValue1,"UTF-8");//URL编码转换
		/*searchParameter作为Dao层设置页面跳转参数*/
		searchParameter="&searchSelect="+searchSelect+"&searchValue="+enSearchValue+"&like="+like;
		
		if(personalType==1){
			searchParameter=searchParameter+"&teacherId="+teacherId;
			pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize,"tableFilesPersonalSearch.action",searchParameter);
			return "personalSearch";
		}
		
		if(personalType==2){
			pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize,"tableFilesPersonalAllSearch.action",searchParameter);
			return "personalAllSearch";
		}
	
		
		pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize,"tableFilesSearch.action",searchParameter);
		
		return "search";
	}
	
	public String Detail() throws Exception {
		// TODO Auto-generated method stub
		tableFiles=(TableFiles)this.getCommonService().findByIntId(tableId, "gdut.jmxywz.been.TableFiles");
		if(tableFiles==null){
			return "error";
		}
		return "detail";
	}
	
	public String PreUpdate() throws Exception {
		// TODO Auto-generated method stub
		tableFiles=(TableFiles)this.getCommonService().findByIntId(tableId, "gdut.jmxywz.been.TableFiles");
		if(tableFiles==null){
			return "error";
		}
		return "preUpdate";
	}
	
	
	public String Update() throws Exception {
		// TODO Auto-generated method stub
		boolean bl=this.getCommonService().updateObject(tableFiles);
		if(!bl){
			return "error";
		}
		
		if(personalType==1)
			return "personalUpdate";
		
		return "update";
	}
	
	public String Delete() throws Exception {
		// TODO Auto-generated method stub
		/*删除文件记录*/
		tableFiles=(TableFiles)this.getCommonService().findByIntId(tableId, "gdut.jmxywz.been.TableFiles");
		if(tableFiles==null){
			return "error";
		}
		
		boolean bl=this.getCommonService().deleteObject(tableFiles);
		if(!bl){
			return "error";
		}
		
		/*删除文件记录之后，删除文件*/
		try{
			File file=new File(ServletActionContext.getServletContext().getRealPath("/")+tableFiles.getTableFileUrl());
			file.delete();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if(personalType==1)
			return "personalDelete";
		
		return "delete";
	}
	
	public String Download() throws Exception {
		// TODO Auto-generated method stub
		tableFiles=(TableFiles)this.getCommonService().findByIntId(tableId, "gdut.jmxywz.been.TableFiles");
		
		fileUrl=tableFiles.getTableFileUrl();
		fileUrl=ServletActionContext.getRequest().getRealPath("")+fileUrl;//将相对路径装换为物理路径
		/*inputStream,fileDownSaveName,contentType对应struts.xml文件中的配置*/
		File file = new File(fileUrl);
		inputStream= new FileInputStream(file);
		
		fileDownSaveName=file.getName();
		contentType=this.getContentType(fileUrl);
		/*下载次数加1*/
		tableFiles.setDownloadTime(tableFiles.getDownloadTime()+1);
		//System.out.println("---------------------------"+teachingFiles.getDownloadtime());
		boolean bl=this.getCommonService().updateObject(tableFiles);
		if(!bl){
			return "error";
		}
		return "download";
	}
	
	public String Audit() throws Exception {
		// TODO Auto-generated method stub
		/*审核，将审核状态存入数据库*/
		tableFiles=(TableFiles)this.getCommonService().findByIntId(tableId, "gdut.jmxywz.been.TableFiles");
		tableFiles.setAuditing(auditType);
		boolean bl=this.getCommonService().updateObject(tableFiles);
		if(!bl){
			return "error";
		}
		
		return "audit";
	}

	
	public String AuditSearch() throws Exception {
		// TODO Auto-generated method stub
		String hql="from TableFiles";
		String searchParameter="";
		
		/*为了实现状态检索后的跳页问题，必须进行状态判断和跳页传参*/
		if(auditState==4||auditState==5){
			hql=hql+" as bf order by bf.uploadTime";
		}else{
			hql=hql+" as bf where bf.auditing="+auditState+" order by bf.uploadTime";
		}

		searchParameter="&auditState="+auditState;
		
		pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize,"tableFilesAuditSearch.action",searchParameter);
		return "auditSearch";
	}

	
/***
 * 教师个人表格列表
 * @return
 * @throws Exception
 */
	public String PersonalShow() throws Exception {
		// TODO Auto-generated method stub
		teacher=(Teacher)ActionContext.getContext().getSession().get(TEACHER_SESSION_KEY);
		if(teacher==null)
			return "input";
		teacherId=teacher.getTeacherId();
		
		String hql="from TableFiles tf where tf.teacher.teacherId="+teacherId+" order by tf.uploadTime desc";
		pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize, "tableFilesPersonalShow.action", "");
		if(pageModel.getList()!=null){
			for(int i=0;i<pageModel.getList().size();i++){
				tableFiles=(TableFiles)pageModel.getList().get(i);
				/*设置日期格式*/
				java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd");
				tableFiles.setUploadTime(df.parse(df.format(tableFiles.getUploadTime())));
			}
		}
		personalType=1;
		return "personalShow";
	}

	
	/***
	 * 一般后台登陆者的表格下载列表
	 * @return
	 * @throws Exception
	 */
	public String PersonalAllShow() throws Exception {
		// TODO Auto-generated method stub
		
		String hql="from TableFiles tf where tf.auditing=1 or tf.auditing=2 order by tf.uploadTime desc";
		pageModel=this.getCommonService().findPage(hql, null, currentPage, pageSize, "tableFilesPersonalAllShow.action", "");
		if(pageModel.getList()!=null){
			for(int i=0;i<pageModel.getList().size();i++){
				tableFiles=(TableFiles)pageModel.getList().get(i);
				/*设置日期格式*/
				java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd");
				tableFiles.setUploadTime(df.parse(df.format(tableFiles.getUploadTime())));
			}
		}
		personalType=2;
		return "personalAllShow";
	}
}
